import React from 'react'
import {connect} from 'react-redux'
import { Form, Select, Row, Col, InputNumber, Input, DatePicker, Button, message, Spin, Icon, Modal, Popover, Alert } from "antd";
import {deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import 'styles/loan-billing/add-loan.scss'
import Chooser from "components/chooser";
import moment from "moment";
import baseService from "share/base.service";
import borrowService from 'containers/loan-billing/borrow-and-return.service';
import VendorChooser from "containers/loan-billing/add-vendor/vendor-chooser";
import NewVendorForm from 'containers/request/new-request/new-vendor-form';
import Condition from 'components/condition';
import config from "config";
const If = Condition.If;
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 14, offset: 1},
};

class AddLoan extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      info: {},
      formInfo: {},
      record: {},
      currencyList: [],
      payeeType: '1002',
      loading: false,
      formTypeList: [],
      defaultAccount: {},
      accountOption: [],
      selectLoading: false,
      selectUser: {},
      spinLoad: false,
      id: '',
      addAccountVisible: false,
      contractInfo: {},
      loanMaxParams: {},
      loanMaxInfo: {},
      loanTypeInfo: {}
    }
  }

  componentWillMount() {
    baseService.getAllCurrencyByLanguage('zh_cn', this.props.user.userOID, true).then(res => {
      this.setState({currencyList: res.data})
    }).catch(e => {
      message.error(e.response.data.message);
    });
  }

  disabledRepayDate = (currentDate) => {
    const { formInfo } = this.state;
    let formCode = formInfo.formCode;
    if (formCode === 'JK004') {
      return (
        currentDate &&
        (currentDate < moment(Date.now()) || currentDate > moment(Date.now()).add(30, 'd'))
      );
    }
    return (
      currentDate &&
      (currentDate < moment(Date.now()) || currentDate > moment(Date.now()).add(60, 'd'))
    );
  };

  componentWillReceiveProps(nextProps) {
    if(nextProps.addShow === this.props.addShow){
      return -1;
    }
    if(!nextProps.addShow){
      this.props.form.resetFields();
      this.setState({
        info: {},
        formInfo: {},
        record: {},
        currencyList: [],
        payeeType: '1002',
        formTypeList: [],
        defaultAccount: {},
        accountOption: [],
        selectUser: {},
        id: '',
        loanMaxParams: {}
      })
    }
    this.props.form.resetFields();
    this.setState({
      info: nextProps.info,
      id: nextProps.recordInfo,
      formInfo: nextProps.formInfo
    },() => {
      this.setState({spinLoad:true});
      Promise.all([
        borrowService.getFormTypeList(this.state.info.formOID),
        this.state.id && this.state.id !== '' && borrowService.getLineDetail(this.state.id)
      ]).then(res => {
        this.setState({
          formTypeList: res[0].data,
          record: res[1] ? res[1].data : {},
          spinLoad: false,
          payeeType: res[1] ? res[1].data.payeeType.toString() : '1002',
          contractInfo: res[1] && res[1].data.contractLineId ? {
            contractLineId: res[1].data.contractLineId,
            contractHeaderId: res[1].data.contractHeaderId,
            availableAmount: res[1].data.contractAssociatedDTO.availableAmount
          } : {}
        },() => {
          const { record, payeeType, info } = this.state;
          if(Object.keys(record).length > 0){
            let temp = [{
              id: record.payeeId,
              fullName: record.payeeName,
              userOID: record.payeeOid,
              venNickname: record.payeeName,
              employeeID: record.payeeCode
            }];
            payeeType === '1002' ? this.chooseUser(temp) : this.chooseVendor(temp,true);
            this.handleLoanMax(record.loanTypeId,'loanTypeId')
          } else {
            this.chooseUser([{
              id: info.applicant.id,
              fullName: info.applicant.fullName,
              userOID: info.applicant.userOID,
              employeeID: info.applicant.employeeID
            }]);
          }
        })
      }).catch(() => {
        this.setState({spinLoad: false});
        message.error(messages('loan-billing.key25')/*系统异常*/);
      });
    })
  };

  handleChangePayeeType = (value) => {
    this.setState({payeeType: value, defaultAccount: {},accountOption: [],selectUser: {}});
    this.handleLoanMax(null, 'payeeId');
    this.props.form.setFieldsValue({payeeId: undefined,payeeAccountNumber: undefined,payeeAccountName: undefined});
  };

  renderPayeeId = () => {
    const { payeeType, info, formInfo, contractInfo } = this.state;
    if(payeeType === '1002'){
      return <Chooser selectorItem={{
                        title: messages('loan-billing.key101')/*选择人员*/,
                        url: `${config.baseUrl}/api/users/v3/search`,
                        searchForm: [{
                          type: 'input',
                          id: 'keyword',
                          label: messages('components.key691')/*工号/姓名/手机号*/
                        },{
                          type: 'select',
                          id: 'companyOID',
                          label: messages('loan-billing.key48')/*公司*/,
                          labelKey: 'name',
                          valueKey: 'companyOID',
                          options: [],
                          method: 'get',
                          getUrl: `${config.baseUrl}/api/company/by/term?page=0&size=999&enabled=${true}&setOfBooksId=${info.setOfBooksId}`
                        }],
                        columns: [
                            {
                              title:  messages('components.key5'/*工号*/),//工号
                              dataIndex: 'employeeID', width: '10%'
                            },
                            {
                              title: messages('components.key6'/*姓名*/),//姓名
                              dataIndex: 'fullName',
                              width: '25%',
                              render: value => {
                                return <Popover placement="topLeft" content={value} overlayStyle={{maxWidth: 500}}>{value}</Popover>
                              }
                            },
                            {
                              title: messages('components.key7'/*手机号*/),//手机号
                              dataIndex: 'mobile',
                              width: '25%',
                              render: value => {
                                return <Popover placement="topLeft" content={value} overlayStyle={{maxWidth: 500}}>{value}</Popover>
                              }
                            },
                            {
                              title: messages('components.key8'/*部门名称*/),//部门名称
                              dataIndex: 'departmentName',
                              width: '20%',
                              render: value => {
                                return <Popover placement="topLeft" content={value} overlayStyle={{maxWidth: 500}}>{value}</Popover>
                              }
                            },
                            {
                              title: messages('components.key9'/*职务*/),//职务
                              dataIndex: 'title',
                              width: '20%',
                              render: value => {
                                return <Popover placement="topLeft" content={value} overlayStyle={{maxWidth: 500}}>{value}</Popover>
                              }
                            },
                        ],
                        key: 'userOID',
                      }}
                      single={true}
                      valueKey="id"
                      labelKey="fullName"
                      itemMap
                      // disabled={Object.keys(contractInfo).length > 0}
                      disabled={true}
                      onChange={this.chooseUser}
                      showClear={false}
                      placeholder={messages('common.select')/*请选择*/}
                      listExtraParams={{
                        status: 1001,
                        roleType: 'TENANT',
                        setOfBooksId: info.setOfBooksId}}/>;
    }else{
      return <VendorChooser single={true}
                            type="vendor_account"
                            placeholder={messages("common.please.select")}
                            labelKey="venNickname"
                            onChange={this.chooseVendor}
                            showClear={false}
                            valueKey="id"
                            itemMap
                            // disabled={Object.keys(contractInfo).length > 0}
                            disabled={true}
                            isNeedBtn={formInfo.customFormPropertyMap['document.venmasteradd.enable'] === 'true'}
                            vendorParams={{
                              companyOID: info.companyOID,
                              userOID: info.applicantOID
                            }}
                            listExtraParams={{
                              companyOid: info.companyOID,
                              companyId: info.companyId
                            }}/>
    }
  };

  chooseUser = (value) => {
    this.handleLoanMax(value[0].id, 'payeeId');
    this.setState({selectLoading: true,selectUser: value[0]});
    borrowService.getUserCompanyAccount(value[0].userOID).then(res => {
      let account = null;
      res.data.map(item => {
        item.isPrimary && (account = item)
      });
      this.setState({
        defaultAccount: account || {},
        accountOption: res.data,
        selectLoading: false
      },() => {
        const { defaultAccount } = this.state;
        this.props.form.setFieldsValue({payeeAccountNumber: defaultAccount.bankAccountNo });
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({selectLoading: false});
    })
  };

  //选择供应商
  chooseVendor = (value,isFirst = false) => {
    this.handleLoanMax(value[0].id, 'payeeId');
    let account = null;
    const { info, record } = this.state;
    if(value[0].venBankAccountBeans){
      value[0].venBankAccountBeans.map(item => {
        item.primaryFlag && (account = item);
      });
      this.setState({
        accountOption: value[0].venBankAccountBeans,
        defaultAccount: account || {},
        selectUser: value[0]
      },() => {
        const { defaultAccount } = this.state;
        this.props.form.setFieldsValue({payeeAccountNumber: defaultAccount.bankAccount,payeeAccountName: defaultAccount.venBankNumberName});
      })
    } else {
      borrowService.getVendorAccount(info.companyOID,info.companyId).then(res => {
        res.data.map(vendorItem => {
          if(vendorItem.id === value[0].id){
            vendorItem.venBankAccountBeans.map(item => {
              item.primaryFlag && (account = item);
            });
            isFirst && (account = {bankAccount: record.payeeAccountNumber,venBankNumberName: record.payeeAccountName});
            this.setState({
              accountOption: vendorItem.venBankAccountBeans,
              defaultAccount: account || {},
              selectUser: vendorItem
            },() => {
              const { defaultAccount } = this.state;
              this.props.form.setFieldsValue({payeeAccountNumber: defaultAccount.bankAccount,payeeAccountName: defaultAccount.venBankNumberName});
            })
          }
        })
      }).catch(e => {
        message.error(e.response.data.message);
      })
    }
  };

  formInitialValue = (key,messageKey) => {
    const { record, info } = this.state;
    let titleItem = undefined;
    info.customFormValues && info.customFormValues.map(item => {
      item.messageKey === messageKey && !(!!record[key]) && (titleItem = item.value);
    });
    return titleItem;
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        const { info, formTypeList, selectUser, payeeType, record, defaultAccount, contractInfo, formInfo } = this.state;
        let formCode = formInfo.formCode
        values = Object.assign({},record,values);
        !values.loanBillId && (values.loanBillId = info.id);
        !values.ownerOid && (values.ownerOid = info.applicant.userOID);
        formTypeList.map(item => {
          item.id == values.loanTypeId && (values.loanTypeName = item.description);
        });
        values.payeeName = payeeType === '1002' ? selectUser.fullName : selectUser.venNickname;
        values.payeeCode = payeeType === '1002' ? selectUser.employeeID : selectUser.venNickOid;
        payeeType === '1002' && (values.payeeOid = selectUser.userOID);
        if (formCode === 'JK004') {
          values.payeeType = parseInt(payeeType)
          values.payeeId = this.state.info.applicant.id;
          values.paymentType = this.state.formInfo.customFormPropertyMap['loan.bill.pay.type'];
        } else {
          values.payeeId && (values.payeeId = values.payeeId[0].id);
          values.payeeType && (values.payeeType = parseInt(values.payeeType));
        }
        delete values.contractHeaderId;
        delete values.contractLineId;
        delete values.contractAssociatedDTO;
        if(Object.keys(contractInfo).length > 0){
          values.contractHeaderId = contractInfo.contractHeaderId;
          values.contractLineId = contractInfo.contractLineId;
        }
        values.planedPaymentDate && (values.planedPaymentDate = moment(values.planedPaymentDate).format('YYYY-MM-DD'));
        values.planedRepaymentDate && (values.planedRepaymentDate = moment(values.planedRepaymentDate).format('YYYY-MM-DD'));
        Object.keys(defaultAccount).length && (values.payeeBankCode = defaultAccount.bankCode);
        info.referenceApplication && (values.refApplicationOid = info.referenceApplication.applicationOID);
        this.setState({loading: true});
        if (formCode === 'JK004' || formCode === 'JK003') {
          if (values.amount > 50000) {
            message.warning('餐厅使用的（临时）找赎备用金借款单借款额度限制最高5万')
            this.setState({loading: false});
          } else {
            borrowService.addLoanLine(values).then(() => {
              this.props.close(true);
              this.setState({loading: false});
              message.success(messages('common.operate.success'));
            }).catch(e => {
              message.error(e.response.data.message);
              this.setState({loading: false});
            });
          }
        } else {
          borrowService.addLoanLine(values).then(() => {
            this.props.close(true);
            this.setState({loading: false});
            message.success(messages('common.operate.success'));
          }).catch(e => {
            message.error(e.response.data.message);
            this.setState({loading: false});
          });
        }
      }
    })
  };

  changeBankAccount = (value) => {
    const { payeeType, accountOption } = this.state;
    let temp = null;
    accountOption.map(item => {
      payeeType === '1002' && item.bankAccountNo === value && (temp = item);
      payeeType === '1001' && item.bankAccount === value && (temp = item);
    });
    this.setState({defaultAccount: temp},() => {
      const { defaultAccount } = this.state;
      this.props.form.setFieldsValue({
        payeeAccountName: payeeType === '1002' ? defaultAccount.bankAccountName : defaultAccount.venBankNumberName
      })
    });
  };

  handleAdd = () => {
    const { selectUser } = this.state;
    Object.keys(selectUser).length ? this.setState({addAccountVisible: true}) : message.error(messages('loan-billing.key92')/*请先选择供应商*/);
  };

  handleNewVendorOk = (result) => {
    let { accountOption } = this.state;
    accountOption.push(result.venBankAccountBeans);
    this.setState({
      addAccountVisible: false,
      defaultAccount: result.venBankAccountBeans,
      accountOption
    },() => {
      const { defaultAccount } = this.state;
      this.props.form.setFieldsValue({payeeAccountNumber: defaultAccount.bankAccount,payeeAccountName: defaultAccount.venBankNumberName});
    })
  };

  handleChangeContract = value => {
    if(value.length === 0){
      this.setState({payeeType: '1002', defaultAccount: {}, accountOption: [], selectUser: {}, contractInfo: {}},() => {
        this.handleLoanMax(null, 'payeeId');
        this.props.form.setFieldsValue({
          payeeType: '1002',
          payeeId: undefined,
          payeeAccountNumber: undefined,
          payeeAccountName: undefined,
          contractLineId: undefined
        });
      });
    } else if (value[0].employeeInfoDTO){
      this.setState({payeeType: '1002', defaultAccount: {}, accountOption: [], selectUser: {}, contractInfo: value[0]},() => {
        this.handleLoanMax(null, 'payeeId');
        let temp = [];
        let res = deepFullCopy(value[0].employeeInfoDTO);
        res.id = res.userID;
        temp.push(res);
        this.props.form.setFieldsValue({
          payeeType: '1002',
          payeeId: temp,
          planedPaymentDate: moment(moment(this.state.contractInfo.dueDate),'YYYY-MM-DD')
        });
        this.chooseUser(temp);
      });
    } else if (value[0].vendorInfoDTO){
      this.setState({payeeType: '1001', defaultAccount: {}, accountOption: [], selectUser: {}, contractInfo: value[0]},() => {
        this.handleLoanMax(null, 'payeeId');
        let temp = [];
        temp.push(value[0].vendorInfoDTO);
        this.props.form.setFieldsValue({
          payeeType: '1001',
          payeeId: temp,
          planedPaymentDate: moment(moment(this.state.contractInfo.dueDate),'YYYY-MM-DD')
        });
        this.chooseVendor(temp);
      });
    }
  };

  handleLoanMax = (value, type) => {
    const { loanMaxParams, formTypeList } = this.state;
    loanMaxParams[type] = value;
    if(type === 'loanTypeId'){
      formTypeList.map(item => {
        item.id === value && this.setState({loanTypeInfo: item});
      })
    }
    this.setState({loanMaxParams},() => {
      if(loanMaxParams.loanTypeId && loanMaxParams.payeeId){
        borrowService.getLoanMax(this.state.loanMaxParams).then(res => {
          this.setState({loanMaxInfo: res.data});
        }).catch(e => {
          message.error(e.response.data.message);
        })
      } else {
        this.setState({loanMaxInfo: {}});
      }
    });
  };

  render(){
    const { info, record, currencyList, loading, formTypeList, accountOption, selectLoading, defaultAccount, formInfo,
      payeeType, spinLoad, addAccountVisible, selectUser, contractInfo, loanMaxInfo, loanTypeInfo } = this.state;
    const { getFieldDecorator } = this.props.form;
    let formCode = formInfo.formCode
    let isNeedContract = formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['loan.property.associated.contract.enabled'] === 'true';
    
    // https://pmo.mcd.com.cn/jira/browse/TES-2118 隐藏银行账号和收款方户号
    // let showPayeeAccountNumber = false // 是否展示收款方银行账户以及收款方户名
    // if (info.customFormValues && info.customFormValues.length > 0) {
    //   info.customFormValues.some((item) => {
    //     if (item.messageKey === 'cust_list') {
    //       if (item.value === '016') { // 不涉及政府官员,则不展示收款方银行账户和收款方户名
    //         showPayeeAccountNumber = false
    //       } else {
    //         showPayeeAccountNumber = true
    //       }
    //       return true
    //     }
    //   })
    // }
    return(
      <div className='add-loan'>
        {
          loanMaxInfo.maxLoanAmount && (
            <Alert style={{marginBottom: '20px'}} message={messages('loan-billing.key126',{arg1: selectUser.fullName || selectUser.venNickname,
              arg2: loanTypeInfo.description,
              arg3: loanMaxInfo.currencyCode,
              arg4: this.filterMoney(loanMaxInfo.remainingLoanAmount,queryCurrencyPrecision(loanMaxInfo.currencyCode),true)
            })} type="warning" showIcon/>
          )
        }
        {
          loanMaxInfo.prepaymentTypeCode && !loanMaxInfo.maxLoanAmount && loanMaxInfo.prepaymentTypeCode !== 1001 && loanMaxInfo.isExistUnRepaidLoanAmount && (
            <Alert style={{marginBottom: '20px'}} message={messages('loan-billing.key127',{
              arg1: selectUser.fullName || selectUser.venNickname,
              arg2: loanTypeInfo.description,
              arg3: loanMaxInfo.prepaymentTypeCode === 1002 ? messages('loan-billing.key128') : messages('loan-billing.key129')
            })} type="warning" showIcon/>
          )
        }
        <Spin spinning={spinLoad}>
          <Form>
            {
              isNeedContract && (
                <FormItem label={messages('loan-billing.key106')/*关联合同*/} {...formItemLayout}>
                  {getFieldDecorator('contractLineId', {
                    initialValue: record.contractLineId ? [{contractLineId: record.contractLineId, contractHeaderId: record.contractHeaderId,contractName: record.contractAssociatedDTO.contractName}] : undefined
                  })(
                    <Chooser listExtraParams={{
                      documentType: 'PREPAYMENT_REQUISITION',
                      companyId: info.companyId,
                      currency: info.currencyCode,
                      partnerId: selectUser.id
                    }}
                             itemMap
                             onChange={this.handleChangeContract}
                             type={'choose_contract'}
                             valueKey="contractLineId"
                             labelKey="contractName"
                             single/>
                  )}
                </FormItem>
              )
            }
            <FormItem label={messages('loan-billing.key12')/*借款类型*/} {...formItemLayout}>
              {getFieldDecorator('loanTypeId', {
                rules: [{
                  required: true,
                  message: messages('common.please.select')
                }],
                initialValue: record.loanTypeId ? record.loanTypeId.toString() : formTypeList && formTypeList[0] && formTypeList[0].id ? formTypeList[0].id : undefined
              })(
                <Select placeholder={messages('common.please.select')/*请选择*/} onChange={value => this.handleLoanMax(value, 'loanTypeId')}>
                  {
                    formTypeList.map(item => {
                      return <Option key={item.id}>{item.description}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            {formCode !== 'JK004' && <FormItem label={messages('loan-billing.key67')/*收款方类型*/} {...formItemLayout}>
              {getFieldDecorator('payeeType', {
                rules: [{
                  required: true,
                  message: messages('common.please.select')
                }],
                initialValue: record.payeeType ? record.payeeType.toString() : payeeType
              })(
                <Select onChange={this.handleChangePayeeType}
                        placeholder={messages('common.please.select')/* 请选择 */}
                        disabled={Object.keys(contractInfo).length > 0}>
                  <Option key={'1002'}>{messages('loan-billing.key14')/*员工*/}</Option>
                  {/* <Option key={'1001'}>{messages('loan-billing.key15')/*供应商*/}
                  {/* </Option> */}
                </Select>
              )}
            </FormItem>}
            {formCode !== 'JK004' && <FormItem label={messages('loan-billing.key68')/*收款方*/} {...formItemLayout}>
              {getFieldDecorator('payeeId', {
                rules: [{
                  required: true,
                  message: messages('common.please.select')
                }],
                initialValue: record.payeeId ?
                  [{id: record.payeeId,fullName: record.payeeName, userOID: record.payeeOid, venNickname: record.payeeName}] :
                    info.applicant ? [{id: info.applicant.id, fullName: info.applicant.fullName, userOID: info.applicant.userOID, employeeID: info.applicant.employeeID}] : undefined
              })(
                this.renderPayeeId()
              )}
            </FormItem>}
            {/* https://pmo.mcd.com.cn/jira/browse/TES-2118 隐藏银行账号和收款方户号 */}
            {/* {showPayeeAccountNumber ? (formCode === 'JK003' || formCode === 'JK004') ? '' : <Row>
              <Col span={21}>
                <FormItem label={'收款方银行账户'} labelCol={{span: 7}} wrapperCol={{span: 16, offset: 1}}>
                  {getFieldDecorator('payeeAccountNumber', {
                    initialValue: Object.keys(defaultAccount).length ? (payeeType === '1002' ? defaultAccount.bankAccountNo : defaultAccount.bankAccount) : record.payeeAccountNumber
                  })(
                    <Select notFoundContent={selectLoading ? <Spin size="small"/> : '无匹配结果'}
                            onChange={this.changeBankAccount} placeholder={'请选择'}>
                      {
                        accountOption.map(item => {
                          return <Option key={payeeType === '1002' ? item.bankAccountNo : item.bankAccount}>
                            {payeeType === '1002' ? item.bankAccountNo : item.bankAccount}
                          </Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
              <If value={payeeType === '1001' && formInfo.customFormPropertyMap['document.venmasteradd.enable'] === 'true'}>
                <Col span={3}>
                  <Icon type="plus-circle" onClick={this.handleAdd} style={{marginLeft:'10px',fontSize:'20px',marginTop:'5px',color:'#108ee9',cursor: 'pointer'}}/>
                </Col>
              </If>
            </Row> : null} */}
            {/* {showPayeeAccountNumber ? <FormItem label={'收款方户名'} {...formItemLayout}>
              {getFieldDecorator('payeeAccountName', {
                initialValue: info.applicant && info.applicant.fullName ? info.applicant.fullName : undefined
              })(
                <Input disabled={true} placeholder={'请输入'}/>
              )}
            </FormItem> : null} */}
            <Row>
              <Col span={6} className="form-define-title required">{messages('loan-billing.key11')/*借款金额*/}：</Col>
              <Col span={3} offset={1}>
                <FormItem>
                  {getFieldDecorator('currencyCode', {
                    initialValue: record.currencyCode ? record.currencyCode : (info.currencyCode ? info.currencyCode : undefined)
                  })(
                    <Select dropdownMatchSelectWidth={false}
                            showSearch={true}
                            disabled={true}
                            optionFilterProp="children"
                            filterOption={(input, option) => option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            placeholder={messages('common.please.select')/* 请选择 */}>
                      {currencyList.map(item => {
                        return <Option key={item.currency}>{item.currency}</Option>
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={10} offset={1}>
                <FormItem>
                  {getFieldDecorator('amount', {
                    rules: [
                      // {
                      // required: true,
                      // message: messages('common.please.enter')
                      // },
                      {
                      validator: (rule, value, callback) => {
                        if (value === null || value === undefined || value === "") {
                          callback(messages('common.please.enter'));
                          return;
                        }
                        let reg = new RegExp('^[1-9]([0-9])*((\\.)([0-9])+){0,1}$','g');
                        if(reg.test(value)){
                          if(contractInfo.availableAmount && Number(value) > contractInfo.availableAmount){
                            callback(messages('loan-billing.key130')/*金额超过合同金额上限*/)
                          } else {
                            callback();
                          }
                        }else{
                          callback(messages('loan-billing.key91')/*请输入正数*/);
                        }
                      }
                    }],
                    initialValue: record.amount ? record.amount : (formCode !== 'JK002' ? (info.referenceApplication ? info.referenceApplication.loanableAmount : contractInfo.availableAmount) : 2000)
                  })(
                    formCode === 'JK002' || formCode === 'JK007' ?
                      <InputNumber
                        formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        min={0} max={contractInfo.availableAmount} precision={2} style={{width: '100%'}} placeholder={messages('common.please.input')/*请输入*/} disabled/> :
                      <InputNumber
                        formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        min={0} max={contractInfo.availableAmount} precision={2} style={{width: '100%'}} placeholder={messages('common.please.input')/*请输入*/}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            {
              isNeedContract &&
              <FormItem label={messages('loan-billing.key109')/*计划付款日期*/} {...formItemLayout}>
                {getFieldDecorator('planedPaymentDate', {
                  initialValue: record.planedPaymentDate ? moment(moment(record.planedPaymentDate).local(),'YYYY-MM-DD') :
                    moment(moment(new Date()),'YYYY-MM-DD')
                })(
                  <DatePicker format="YYYY-MM-DD" placeholder={messages('common.please.select')/* 请选择 */}/>
                )}
              </FormItem>
            }
            {['JK003', 'JK002'].includes(formCode) ? '' : <FormItem label={messages('loan-billing.key23')/*计划还款日期*/} {...formItemLayout}>
              {getFieldDecorator('planedRepaymentDate', {
                rules: [{
                  required: formCode === 'JK001' || formCode === 'JK004' ? true : false,
                  message: messages('common.please.select')
                }],
                initialValue: record.planedRepaymentDate ? moment(moment(record.planedRepaymentDate).local(),'YYYY-MM-DD') :
                  this.formInitialValue('planedRepaymentDate', 'date') ? moment(moment(this.formInitialValue('planedRepaymentDate', 'date')).local(), 'YYYY-MM-DD') : undefined
              })(
                <DatePicker showToday={false} format="YYYY-MM-DD" disabledDate = {this.disabledRepayDate} placeholder={messages('common.please.select')/* 请选择 */}/>
              )}
            </FormItem>}
            {info.referenceApplication && info.referenceApplication.businessCode && (
              <FormItem label={messages('loan-billing.key71')/*关联申请单*/} {...formItemLayout}>
                {getFieldDecorator('refApplicationBusinessCode', {
                  initialValue: info.referenceApplication.businessCode
                })(
                  <Input disabled={true} placeholder={messages('common.please.input')/*请输入*/}/>
                )}
              </FormItem>
            )}
            {formCode !== 'JK004' && <FormItem label={messages('loan-billing.key24')/*付款方式类型*/} {...formItemLayout}>
              {getFieldDecorator('paymentType', {
                rules: [{
                  required: true,
                  message: messages('common.please.select')
                }],
                initialValue: formInfo.customFormPropertyMap ? formInfo.customFormPropertyMap['loan.bill.pay.type'] : undefined
              })(
                <Select disabled={true} placeholder={messages('common.please.select')/* 请选择 */}>
                  <Option key={'ONLINE_PAYMENT'}>{messages('loan-billing.key20')/*线上*/}</Option>
                  <Option key={'OFFLINE_PAYMENT'}>{messages('loan-billing.key21')/*线下*/}</Option>
                  <Option key={'EBANK_PAYMENT'}>{messages('loan-billing.key22')/*落地文件*/}</Option>
                </Select>
              )}
            </FormItem>}
            <FormItem label={messages('common.loan.reason')/*借款原因*/} {...formItemLayout}>
              {getFieldDecorator('remark', {
                rules: [{
                  required: true,
                  message: messages('common.please.enter')
                }],
                initialValue: record.remark ? record.remark : this.formInitialValue('remark', 'title')
              })(
                <TextArea placeholder={messages('common.max.characters.length', {max: 200})} rows={3}
                          style={{resize: 'none'}}/>
              )}
            </FormItem>
          </Form>
        </Spin>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={loading}> {messages('common.save')/*保存*/}
          </Button>
          <Button onClick={() => {this.props.close()}}>{messages('common.cancel')}</Button>
        </div>
        <Modal visible={addAccountVisible}
               wrapClassName="new-vendor-modal"
               title={messages('loan-billing.key93')/*添加银行卡号*/}
               cancelText={messages('common.back')/*返回*/}
               width={700}
               onCancel={() => {
                 this.setState({addAccountVisible: false});
               }}
               footer={null}>
          <NewVendorForm newVendorVisible={addAccountVisible}
                         onCancel={() => {
                           this.setState({addAccountVisible: false});
                         }}
                         payeeInfo={selectUser}
                         userOid={info.applicantOID}
                         companyOid={info.companyOID}
                         currentVendor={{}}
                         onOk={this.handleNewVendorOk}/>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language
  }
}

const WrappedAddLoan = Form.create()(AddLoan);
export default connect(mapStateToProps)(WrappedAddLoan);
